<template>
	<div ref="elementRef" :class="[
		'fade-section',
		animation,
		{ 'in-view': isVisible }
	]">
		<slot />
	</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
	animation: {
		type: String,
		default: 'fade-up', // fade-left / zoom-in 等等
	},
	threshold: {
		type: Number,
		default: 0.2,
	},
})

const elementRef = ref(null)
const isVisible = ref(false)

let observer

onMounted(() => {
	observer = new IntersectionObserver(
		([entry]) => {
			isVisible.value = entry.isIntersecting
		},
		{
			threshold: props.threshold,
		}
	)
	if (elementRef.value) {
		observer.observe(elementRef.value)
	}
})

onBeforeUnmount(() => {
	if (elementRef.value && observer) {
		observer.unobserve(elementRef.value)
	}
})
</script>

<style scoped>
.fade-section {
	opacity: 0;
	transform: translateY(50px);
	transition: all 0.6s ease;
}

/* 进入视口时触发 */
.in-view {
	opacity: 1;
	transform: translateY(0);
}

/* 其他动画样式 */
.fade-up {
	transform: translateY(50px);
}

.fade-down {
	transform: translateY(-50px);
}

.fade-left {
	transform: translateX(50px);
}

.fade-right {
	transform: translateX(-50px);
}

.zoom-in {
	transform: scale(0.9);
}

.in-view.fade-up,
.in-view.fade-down,
.in-view.fade-left,
.in-view.fade-right,
.in-view.zoom-in {
	transform: none;
}
</style>